package com.samuel.blog.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.samuel.blog.bean.PageBean;
import com.samuel.blog.constant.CommonConstant;
import com.samuel.blog.controller.BaseController;
import com.samuel.blog.entity.ArticleEntity;
import com.samuel.blog.entity.AuthorEntity;
import com.samuel.blog.entity.TagEntity;
import com.samuel.blog.service.ArticleService;
import com.samuel.blog.service.AuthorService;
import com.samuel.blog.service.TagService;
import com.samuel.blog.utils.ImageUtils;
import com.samuel.blog.utils.ResponseWriteUtils;
import com.samuel.blog.utils.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("admin")
public class ArticleController extends  BaseController {

	private static final long serialVersionUID = -9184847266915273697L;
	private static final Logger logger = Logger.getLogger(ArticleController.class);
	private static final String PRE = "article/";
	private static final String PRE_PAGER = "admin/article_";
	
	@Resource(name = "articleService")
	private ArticleService articleService;
	@Resource(name = "authorService")
	private AuthorService authorService;
	@Resource(name = "tagService")
	private TagService tagService;

	/**
	 * 进入全部列表页
	 */
	@RequestMapping(value = PRE+"list"+SUFFIX, method =  RequestMethod.GET)
	public String toList(HttpServletRequest request) {
		this.configCss(request, "article", "article_all");
		return PRE_PAGER+"list";
	}
	
	@RequestMapping(value = PRE+"list"+SUFFIX, method =  RequestMethod.POST)
	@ResponseBody
	public String list(PageBean pageBean, HttpServletResponse response) {
		PageInfo<AuthorEntity> pageInfo = authorService.selectPage(pageBean, null);
		returnTableData(pageBean, pageInfo, response);
		return null;
	}
	
	/**
	 * 全部进入个人文章列表页
	 * @return
	 */
	@RequestMapping(value = PRE+"page"+SUFFIX, method =  RequestMethod.GET)
	public String page(String authorId, HttpServletRequest request) {
		
		this.configCss(request, "article", "article_all");
		if (StringUtils.empty(authorId)) {
			request.setAttribute("message", "参数不对！");
			return MESSAGE_PAGE;
		}
		request.setAttribute("authorId", authorId);
		return PRE_PAGER+"detail_list";
	}
	
	/**
	 * 从全部进入个人文章列表页
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = PRE+"page"+SUFFIX, method =  RequestMethod.POST)
	public String page(PageBean pageBean, String authorId, String title, HttpServletRequest request, HttpServletResponse response) {
		String message;
		if (StringUtils.empty(authorId)) {
			message = "刷新页面重试！";
			logger.error("authorId 是必须的!");
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		AuthorEntity author = authorService.selectById(authorId);
		if (null == author) {
			message = "这个作者不存在！";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		Map<String, Object> articleParam = new HashMap<>();
		articleParam.put("authorId", authorId);
		if (!StringUtils.empty(title)) {
			articleParam.put("title", title);
		}
		PageInfo<ArticleEntity> selectPage = articleService.selectPage(pageBean, articleParam);
		
		returnTableData(pageBean, selectPage, response);
		return null;
	}
	
	
	/**
	 * 进入个人文章列表页
	 * @return
	 */
	@RequestMapping(value = PRE+"mylist"+SUFFIX, method =  RequestMethod.GET)
	public String mylist(HttpServletRequest request) {
		
		this.configCss(request, "article", "article_me");
		
		AuthorEntity authorEntity = (AuthorEntity)request.getSession().getAttribute(CommonConstant.USER_LOGIN_SESSION_KEY);
		request.setAttribute("authorId", authorEntity.getAuthorId());
		return PRE_PAGER+"detail_list";
	}
	
	/**
	 * 进入修改页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = PRE+"edit"+SUFFIX, method = RequestMethod.GET)
	public String edit(HttpServletRequest request, String articleId) {
		if (StringUtils.empty(articleId)) {
			logger.error("参数不对， 冇得文章主键");
			request.setAttribute("message", "参数不对！");
			return MESSAGE_PAGE;
		}
		ArticleEntity articleEntity = articleService.selectById(articleId);
		// 查询这个文章所拥有的标签
		List<TagEntity> tagList = tagService.selectByArticleId(articleId);
		request.setAttribute("article", articleEntity);
		request.setAttribute("tagList", tagList);
		return PRE_PAGER+"input";
	}
	
	/**
	 * 进入查看页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = PRE+"view/{articleId}"+SUFFIX, method = RequestMethod.GET)
	public String view(HttpServletRequest request, @PathVariable String articleId) {
		if (StringUtils.empty(articleId)) {
			logger.error("参数不对， 冇得文章主键");
			request.setAttribute("message", "参数不对！");
			return MESSAGE_PAGE;
		}
		this.configCss(request, "article", "article_me");
		ArticleEntity articleEntity = articleService.selectById(articleId);

		// 查询这个文章所拥有的标签
		List<TagEntity> tagList = tagService.selectByArticleId(articleId);
		request.setAttribute("article", articleEntity);
		request.setAttribute("tagList", tagList);
		return PRE_PAGER+"view";
	}
	
	/**
	 * 进入添加页面
	 */
	@RequestMapping(value = PRE+"add"+SUFFIX, method = RequestMethod.GET)
	public String add(HttpServletRequest request) {
		this.configCss(request, "article", "article_me");
		return PRE_PAGER+"input";
	}
	
	@RequestMapping(value = PRE+"save"+SUFFIX, method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request, HttpServletResponse response, ArticleEntity article, String tagIds) {
		try {
			String message = "保存文章对象成功！";
			if (null == article) {
				message = "请填写必填项！";
				logger.error(message);
				ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
				return null;
			}
			if (StringUtils.empty(article.getTitle())) {
				message = "请填写标题！";
				logger.error(message);
				ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
				return null;
			}
			if (StringUtils.empty(article.getContent())) {
				message = "请填写内容！";
				logger.error(message);
				ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
				return null;
			}
			AuthorEntity author = (AuthorEntity)request.getSession().getAttribute(CommonConstant.USER_LOGIN_SESSION_KEY);
			article.setAuthorId(author.getAuthorId());
			article.setCreateDate(new Date());
			String[] tagIdList = tagIds.split(",");
			int num = articleService.save(article, Arrays.asList(tagIdList));
			if (num > 0) {
				ajax(response, CommonConstant.NoticeCode.SUCCESS_ONE, message);
			} else {
				message = "系统保存失败！";
				logger.error(message);
				ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			String message = "系统保存失败！";
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
		}
		return null;
	}
	
	@RequestMapping(value = PRE+"update"+SUFFIX, method = RequestMethod.POST)
	@ResponseBody
	public String update(HttpServletRequest request, HttpServletResponse response, ArticleEntity article, String tagIds) {
		try {
			
			String message = "修改文章成功！";
			if (StringUtils.empty(article.getArticleId())) {
				message = "请填写内容！";
				logger.error(message);
				ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
				return null;
			}
			ArticleEntity ae = articleService.selectById(article.getArticleId());
			if (null == ae) {
				message = "请刷新内容内容重试！";
				logger.error(article.getArticleId() + "记录不存在");
				ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
				return null;
			}
			AuthorEntity author = (AuthorEntity)request.getSession().getAttribute(CommonConstant.USER_LOGIN_SESSION_KEY);
			if (!ae.getAuthorId().equals(author.getAuthorId())) {
				message = "你没有权限修改次文章！";
				logger.error(author.getAuthorId() + "： " + author.getUserName() + "没有权限修改此文章！");
				ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
				return null;
			}
			article.setModiftyDate(new Date());
			int num = articleService.update(article, Arrays.asList(tagIds.split(",")));
			if (num > 0) {
				logger.info("修改文章成功！");
				ajax(response, CommonConstant.NoticeCode.SUCCESS_ONE, message);
			} else {
				message = "系统修改失败！";
				logger.error(message);
				ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			String message = "系统修改失败！";
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
	}

	/**
	 * 上传图片 
	 * @param response
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@ResponseBody
	@RequestMapping(value = PRE+"upload"+SUFFIX, method = RequestMethod.POST)
	public String upload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value="file",required=false) MultipartFile[] files) 
			throws IllegalStateException, IOException {
		logger.info("开始上传图片");
		JSONObject map = new JSONObject();
		if (files == null) {
			logger.warn("请上传图片！");
			map.put("errno", 1);
			ResponseWriteUtils.writeJson(response, map);
		} else {
			List<String> listPath = new ArrayList<>();
			for (MultipartFile file : files) {
				String url = ImageUtils.uploadServer(file);
				listPath.add(url);
			}
			map.put("errno", 0);
			map.put("data", listPath);
			logger.info("结束上传图片");
			ResponseWriteUtils.writeJson(response, map);
		}
		return null;
	}

	/**
	 * 进入这个标签相关文章的页面
	 *
	 * @param request
	 * 		请求域
	 * @return 标签文章页
	 */
	@GetMapping("tag")
	public String toTag(HttpServletRequest request, String tagId) {
		this.configCss(request, "tag", "tag_list");
		request.setAttribute("tagId", tagId);
		return PRE_PAGER + "tag_list";
	}

	@ResponseBody
	@PostMapping("tag")
	public String tag(HttpServletRequest request, HttpServletResponse response, PageBean pageBean, String tagId) {
		//  分页获取这个标签下所有的文章
		PageInfo<ArticleEntity> pageInfo = articleService.selectPageByTag(pageBean, tagId);
		returnTableData(pageBean, pageInfo, response);
		return null; 
	}

}
